package org.example;

import lombok.extern.slf4j.Slf4j;
import org.example.config.RPCConfig;
import org.example.config.RegistryConfig;
import org.example.registry.RegistryFactory;
import org.example.registry.IRegistry;
import org.example.utils.ConfigUtils;

/**
 * rpc 框架应用
 */
@Slf4j
public class RPCApplication {

    private static volatile RPCConfig rpcConfig;

    public static void init(RPCConfig newRpcConfig) {
        rpcConfig = newRpcConfig;
        log.info("rpc init, config = {}", newRpcConfig.toString());
        // 注册中心初始化
        RegistryConfig registryConfig = rpcConfig.getRegistryConfig();
        IRegistry registry = RegistryFactory.getInstance(registryConfig.getRegistry());
        registry.init(registryConfig);
        log.info("registry init, config = {}", registryConfig);

        // 创建并注册 ShutdownHook，JVM 退出时执行操作
//        Runtime.getRuntime().addShutdownHook(new Thread(registry::destroy));
    }

    public static void init() {
        RPCConfig config = null;
        try {
            config = ConfigUtils.loadConfig(RPCConfig.class, "rpc");
            config.setRegistryConfig(ConfigUtils.loadConfig(RegistryConfig.class, "registry"));
        } catch (Exception e) {
            log.error("rpc init error", e);
            config = new RPCConfig();
        }
        init(config);
    }

    public static RPCConfig getConfig() {
        if (rpcConfig == null) {
            synchronized (RPCApplication.class) {
                if (rpcConfig == null) {
                    init();
                }
            }
        }
        return rpcConfig;
    }
}
